package rus.webapp.util;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import rus.model.ContentImage;
import rus.service.ContentImageManager;

public class RetrieveImageServlet extends HttpServlet {

	private static final long serialVersionUID = -5226225516230534814L;

	private ApplicationContext ctx = null;

	/**
	 * Initializes the servlet.
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
	}

	/**
	 * Destroys the servlet.
	 */
	public void destroy() {
	}

	/**
	 * Handles the HTTP <code>GET</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 */
	public String getServletInfo() {
		return "Servlet request cards statistic from webService and create chart";
	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String URI = StringUtils.removeStart(request.getRequestURI(), request
				.getContextPath()
				+ "/resource/image/");

		ContentImageManager contentImageManager = (ContentImageManager) ctx
				.getBean("contentImageManager");

		ContentImage contentImage;
		contentImage = contentImageManager.retrieveContentImageByURI(URI);
		if (contentImage != null) {

			byte[] imageData = contentImage.getData();

			OutputStream out = response.getOutputStream();
			response.addHeader("Cache-Control", "no-cache,no-store,max-age=0");
			response.addHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 1);
			response.setContentLength(imageData.length);
			out.write(imageData);
			out.close();
		}
	}
}
